package p1.view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;

import generic.genetic.GeneticAlgorithm;

import javax.swing.JLabel;
import javax.swing.JPanel;

import org.math.plot.Plot2DPanel;
import org.math.plot.plotObjects.BaseLabel;
import org.math.plot.plotObjects.Line;

public class GA_Panel extends JPanel {

	private static final long serialVersionUID = 3373884873730805677L;
	private GeneticAlgorithm ga;
	private Plot2DPanel plot;
	private JLabel label;
	
	public GA_Panel(GeneticAlgorithm ga){
		this.ga = ga;
		
		this.setLayout(new BorderLayout());
		
		plot = new Plot2DPanel();
		
		// define your data
		double[] x = new double[ga.getMax_num_generations()];
		for (int i=0;i<ga.getMax_num_generations();i++) x[i] = i;
		
		
		// add a title
		
		BaseLabel title = new BaseLabel(ga.getTitle(), Color.BLACK, 0.5, 1.1);
		title.setFont(new Font("Courier", Font.PLAIN, 14));
		plot.addPlotable(title);
		
		// define the legend position
		plot.addLegend("SOUTH");
		// add a line plot to the PlotPanel
		plot.addLinePlot("Mejor absoluto", x, ga.bestEver);
		plot.addLinePlot("Mejor de la generacion", x, ga.bestGen);
		plot.addLinePlot("Media de la generacion", x, ga.avgGen);
		
		plot.addPlotable(new Line(Color.CYAN, 
				new double[]{ga.firstGenBestChrom,plot.plotCanvas.base.baseCoords[1][0]},
				new double[]{ga.firstGenBestChrom,plot.plotCanvas.base.baseCoords[1][1]})				
		);
		
		this.add(plot, BorderLayout.CENTER);
		label = new JLabel(ga.getBestChromosome().getString());
		this.add(label, BorderLayout.SOUTH);
	}
	
	public void run(){
		ga.run();
		
		plot.removeAllPlots();
		plot.removeAllPlotables();
		
		BaseLabel title = new BaseLabel(ga.getTitle(), Color.BLACK, 0.5, 1.1);
		title.setFont(new Font("Courier", Font.PLAIN, 14));
		plot.addPlotable(title);
		
		double[] x = new double[ga.getMax_num_generations()];
		for (int i=0;i<ga.getMax_num_generations();i++) x[i] = i;
		plot.addLinePlot("Mejor absoluto", x, ga.bestEver);
		plot.addLinePlot("Mejor de la generacion", x, ga.bestGen);
		plot.addLinePlot("Media de la generacion", x, ga.avgGen);
		
		plot.addPlotable(new Line(Color.CYAN, 
				new double[]{ga.firstGenBestChrom,plot.plotCanvas.base.baseCoords[1][0]},
				new double[]{ga.firstGenBestChrom,plot.plotCanvas.base.baseCoords[1][1]})				
		);
		
		label.setText(ga.getBestChromosome().getString());
		this.validate();
		
	}
}
